package com.telenav.network;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Vector;

import com.google.protobuf.ByteString;
import com.telenav.j2me.datatypes.ProtocolBuffer;
import com.telenav.j2me.datatypes.ProtocolBufferUtil;
import com.telenav.protobuf.ActivityDetailProtoReq;
import com.telenav.protobuf.ActivityListProtoReq;
import com.telenav.protobuf.PortraitProtoReq;
import com.telenav.protobuf.UserProtoReq;
import com.telenav.util.HostList;

public class NetworkProxy {
	
	INetworkCallback callback;
	
	public NetworkProxy(INetworkCallback callback)
	{
		this.callback = callback;
	}
	
	public void sendRequest(Map<String, Object> params, String action)
	{
		ProtocolBuffer pb = new ProtocolBuffer();
        if(action.equals(INetworkProxyConstants.ACT_ACTIVITY_LIST))
        {
        	ActivityListProtoReq.ActivityList req = ActivityListProtoReq.ActivityList.newBuilder()
            		.setStartindex(Integer.parseInt(params.get("startindex").toString()))
            		.setEndindex(Integer.parseInt(params.get("endindex").toString())).build();
            pb.setBufferData(req.toByteArray());
        }
        else if(action.equals(INetworkProxyConstants.ACT_ACTIVITY_DETAIL))
        {
        	ActivityDetailProtoReq.ActivityDetail req = ActivityDetailProtoReq.ActivityDetail.newBuilder()
        			.setId(Integer.parseInt(params.get("id").toString())).build();
        	pb.setBufferData(req.toByteArray());
        }
        else if(action.equals(INetworkProxyConstants.ACT_PERSONAL_INFO))
        {
        	UserProtoReq.User req = UserProtoReq.User.newBuilder().setUsername(params.get("username").toString()).build();
        	pb.setBufferData(req.toByteArray());
        }
        else if(action.equals(INetworkProxyConstants.ACT_PORTRAIT))
        {
        	Object obj = params.get("portrait");
        	PortraitProtoReq.Portrait req = PortraitProtoReq.Portrait.newBuilder()
        			.setUsername(params.get("username").toString()).setImage(ByteString.copyFrom((byte[])obj)).build();
        	pb.setBufferData(req.toByteArray());
        }

        pb.setObjType(action);
        Vector<ProtocolBuffer> reqList = new Vector<ProtocolBuffer>();
        reqList.addElement(pb);
        
		final byte[] buffer = ProtocolBufferUtil.listToByteArray(reqList);
		HttpURLConnection conn = null;
    	try
    	{
    		URL url = new URL(HostList.APP_URL + "/activity");
    		conn = (HttpURLConnection)url.openConnection();
    		conn.setRequestMethod("POST");
    		conn.setDoOutput(true);
    		conn.setDoInput(true);
    		conn.setUseCaches(false);
    		OutputStream os = conn.getOutputStream();
    		os.write(buffer);
    		
    		if(conn.getResponseCode() == HttpURLConnection.HTTP_OK)
    		{	
    			ByteArrayOutputStream bos = new ByteArrayOutputStream();
    			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
    			try 
    			{
    				int numBytesRead;
    				byte[] buf = new byte[256];
    				while ((numBytesRead = bis.read(buf)) != -1) 
    				{
    					bos.write(buf, 0, numBytesRead);
    				}
    			}
    			catch(Exception e)
    			{
    				e.printStackTrace();
    			}
    			
    			handleResponse(bos.toByteArray());
    			
    			bos.close();
    			bis.close();
    		}
    		else
    		{

    		}
    		
    	}
    	catch(Exception e)
    	{
    		System.out.println(e.getMessage());
    	}
    	finally
    	{
    		if(conn != null)
    		{
    			conn.disconnect();
    		}
    	}
	}
	
	public void handleResponse(byte[] response) {
        ProtocolBuffer[] bufs = ProtocolBufferUtil.toBufArray(response);
        if (bufs == null)
            return;
        callback.handleProtocolBuffer(bufs[0]);
	}

}
